package com.datastructure.hashtab;

import java.util.Scanner;

//Hash表的组织架构其实就是数据加上单向链表，数组中存放的是单向链表
public class HashTab {

    public static void main(String[] args) {

        // 创建哈希表
        HashTab hashTab = new HashTab(7);

        //写一个简单的菜单
        String key = "";
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("add: 添加雇员");
            System.out.println("list: 显示雇员");
            System.out.println("find: 查找雇员");
            System.out.println("exit: 退出系统");

            key = scanner.next();
            switch (key) {
                case "add":
                    System.out.println("输入id");
                    int id = scanner.nextInt();
                    System.out.println("输入名字");
                    String name = scanner.next();
                    // 创建雇员
                    Emp emp = new Emp(id, name);
                    hashTab.add(emp);
                    break;
                case "list":
                    hashTab.list();
                    break;
                case "find":
                    System.out.println("请输入要查找的id");
                    id = scanner.nextInt();
                    hashTab.findEmpById(id);
                case "exit":
                    scanner.close();
                    System.exit(0);
                default:
                    break;
            }
        }
    }
    EmpLinkedList[] empLinkedListArr;
    public HashTab(int size){
        empLinkedListArr = new EmpLinkedList[size];
        for(int i=0; i < empLinkedListArr.length; i++){
            empLinkedListArr[i] = new EmpLinkedList();
        }
    }

    public void add(Emp emp){
        int empLinkedListNo = hashFun(emp.id);
        empLinkedListArr[empLinkedListNo].addByOrder(emp);
    }

    public void list(){ //遍历整个hash表
        for(int i = 0; i < empLinkedListArr.length; i++){
            empLinkedListArr[i].list(i);
        }
    }

    public void findEmpById(int id){
        // 返回该员工应该加入到哪条链表
        int empLinkedListNo = hashFun(id);
        Emp emp = this.empLinkedListArr[empLinkedListNo].findEmpById(id);
        if(emp != null){
            System.out.printf("在第%d找到id=%d name=%s\n",(empLinkedListNo+1),id,emp.name);
        } else {
            System.out.printf("没有找到ID为%d\n",id);
        }
    }
    private int hashFun(int id) {
        return id % empLinkedListArr.length;
    }
}
